<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Auth;
use Cookie;

class Cart extends Model
{
    protected $fillable = [
    	'goods_id', 'user_id', 'attrs', 'quantity'
    ];

    public function addToCart($data)
    {
    	$user = Auth::user();
    	if($user)
    	{
    		$carts = $user->carts()->where('goods_id', $data['goods_id'])->first();
    		if($carts)
    		{
    			$carts->increment('quantity');
    		}
    	}
    	else
    	{
    		$datas = json_encode($data);
    		Cookie::queue('name', $datas, 3600 * 34 * 7);
    	}


    	$res = Auth::check() ? Auth::user()->carts()->create($data):self::create($data);
    	return $res ? ['status' => 0] : ['status' => 1];
    }

    public function goods()
    {
        return $this->belongsTo('App\Models\Goods', 'goods_id');
    }

    public function getprice()
    {
        return $this->goods->price * $this->quantity;
    }
}
